﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint.Client;

namespace CloudAppCsomDemoWeb.Pages {

  public class appWebLists : IHttpHandler {

    public void ProcessRequest(HttpContext httpContext) {

      string appWebUrl = HttpContext.Current.Cache["SPAppWebUrl"].ToString();

      using (ClientContext clientContext = new ClientContext(appWebUrl)) {

        // use CSOM to retrieve collection of lists
        Web appWeb = clientContext.Web;
        ListCollection appWebLists = appWeb.Lists;
        clientContext.Load(clientContext.Web);
        clientContext.Load(clientContext.Web.Lists);
        clientContext.ExecuteQuery();

     
        // set up HtmlTextWriter to write to response output stream
        httpContext.Response.ContentType = "text/html";
        StreamWriter innerWriter = new StreamWriter(httpContext.Response.OutputStream);
        HtmlTextWriter writer = new HtmlTextWriter(innerWriter);

        // create an HTML ol element with list of lists in app web
        writer.RenderBeginTag(HtmlTextWriterTag.Ol);
        foreach (var list in appWebLists) {
          writer.RenderBeginTag(HtmlTextWriterTag.Li);
          writer.Write(list.Title);
          writer.RenderEndTag(); // </li>
        }
        writer.RenderEndTag(); // </ol>

        writer.Flush();
        writer.Dispose();
      }

    }

    public bool IsReusable {
      get {
        return false;
      }
    }
  }
}